/********************************************************************************
 * Copyright (c) 2019-2020 [Open Lowcode SAS](https://openlowcode.com/)
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0 .
 *
 * SPDX-License-Identifier: EPL-2.0
 ********************************************************************************/

package org.openlowcode.module.system.action;

import java.util.HashMap;
import java.util.function.Function;

import org.openlowcode.module.system.action.generated.AbsSeeprivilegesAction;
import org.openlowcode.module.system.data.Appuser;
import org.openlowcode.module.system.data.Authority;
import org.openlowcode.module.system.page.SeeprivilegesPage;
import org.openlowcode.server.data.storage.QueryFilter;
import org.openlowcode.server.data.storage.TableAlias;
import org.openlowcode.server.graphic.SPage;
import org.openlowcode.server.runtime.OLcServer;
import org.openlowcode.server.runtime.SModule;

/**
 * Action to gather the privileges (authorities granted to the user) for the
 * current user
 * 
 * @author <a href="https://openlowcode.com/" rel="nofollow">Open Lowcode
 *         SAS</a>
 *
 */
public class SeeprivilegesAction
		extends
		AbsSeeprivilegesAction {
	/**
	 * Creates the action
	 * 
	 * @param parent parent module
	 */
	public SeeprivilegesAction(SModule parent) {
		super(parent);

	}

	@Override
	public ActionOutputData executeActionLogic(Function<TableAlias, QueryFilter> datafilter) {
		Authority[] authorities = OLcServer.getServer().getSecuritymanager().getAuthoritiesForCurrentUser();
		HashMap<String, Authority> uniqueauthorities = new HashMap<String, Authority>();
		for (int i = 0; i < authorities.length; i++)
			uniqueauthorities.put(authorities[i].getNr(), authorities[i]);
		Authority[] finalauthorities = uniqueauthorities.values().toArray(new Authority[0]);
		Appuser user = OLcServer.getServer().getCurrentUser();
		String usersummary = "You are logged in as " + user.getObjectname() + " (" + user.getNr() + ").";
		return new ActionOutputData(usersummary, finalauthorities);
	}

	@Override
	public SPage choosePage(ActionOutputData logicoutput) {
		return new SeeprivilegesPage(logicoutput.getUsersummary(), logicoutput.getUserauthorities());
	}

}
